const xlsx = require('xlsx')
const fs = require('fs')
const { log } = require('console')

const writeXlsx = (result) => {
  const headers = ['等级', '标签', '区服', '价格', '总评分', '仙玉数量', '金币数量', '银币数量', '物理伤害', '法术伤害', '速度', '物理防御', '法术防御', '治疗强度', '气血上限']

  // 为了效率，解析一次 equip_desc
  const equipDesc = JSON.parse(result.equip.equip_desc).basic

  const data = [
    result.equip.level_desc,
    result.equip.highlights.join('  '),
    result.equip.area_name + result.equip.server_name,
    result.equip.price,
    result.equip.desc_sumup_short,
    equipDesc.iXianYu,
    equipDesc.iGold,
    equipDesc.iSilver,
    equipDesc.iDamage,
    equipDesc.iMagDam,
    equipDesc.iSpeed,
    equipDesc.iDefense,
    equipDesc.iMagDef,
    equipDesc.iHeal,
    equipDesc.iHp_Max
  ]
  // console.log(result.equip.desc_sumup_short)
  const wb = xlsx.utils.book_new()
  let ws

  try {
    const existingWb = xlsx.readFile('data.xlsx')
    ws = existingWb.Sheets['Sheet1']

    const existingHeaders = xlsx.utils.sheet_to_json(ws, { header: 1 })[0]
    if (existingHeaders && existingHeaders.length === headers.length && existingHeaders.every((val, index) => val === headers[index])) {
      // 如果表头存在，就在有数据的下一行填充 data 里面的数据
      const wsData = xlsx.utils.sheet_to_json(ws, { header: 1 })
      wsData.push(data)
      ws = xlsx.utils.aoa_to_sheet(wsData)
      existingWb.Sheets['Sheet1'] = ws
      xlsx.writeFile(existingWb, 'data.xlsx')
    } else {
      throw new Error('表头不匹配，无法添加数据')
    }
  } catch (error) {
    ws = xlsx.utils.aoa_to_sheet([headers, data])
    xlsx.utils.book_append_sheet(wb, ws, 'Sheet1')
    xlsx.writeFile(wb, 'data.xlsx')
  }
}

module.exports = writeXlsx
